/**
 * 页面：后台管理 - 订单管理
 * 功能：分页表格展示、关键词搜索、添加/编辑（抽屉 + 表单）、删除确认、导出按钮
 * 数据：通过封装的 http 客户端访问 /list（包含兼容多种返回结构的解析）
 */
import { Button, Drawer, Select, Spin } from 'antd';
import { Space, Table, Form, Input, message, Popconfirm } from 'antd';
import { PlusOutlined, DownloadOutlined, SearchOutlined } from '@ant-design/icons';
import { useEffect, useState } from 'react';
import pp from '../../api/http';

function Index() {
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useState(5);
  const [open, setOpen] = useState(false);
  const [title, settitle] = useState('');
  const [form] = Form.useForm();
  const [id, setId] = useState('');
  const [loading, setLoading] = useState(true);
  
  // 基于本地登录信息的简单 RBAC：用户名以 admin 开头在登录时被标记为 admin 角色
  let role: string | null = null
  try {
    const raw = localStorage.getItem('auth_user')
    role = raw ? (JSON.parse(raw)?.role || null) : null
  } catch {
    role = null
  }
  const isAdmin = role === 'admin';

  // 获取列表数据（对接本地后端：GET /api/house）
  const getList = async () => {
    try {
      const res = await pp.get('/api/house', {
        params: { page, pageSize }
      })
      const data = res?.data?.data
      const rows = data?.list || []
      const totalCount = data?.total || 0
      setList(rows)
      setTotal(totalCount)
    } catch (error) {
      console.error('获取数据失败:', error)
      message.error('获取数据失败')
    }
  };

  // 页面进入后延迟3秒再加载数据
  useEffect(() => {
    const timer = setTimeout(() => {
      setLoading(false);
    }, 3000);
    return () => clearTimeout(timer);
  }, []);

  // 在非loading时，根据分页变化加载数据
  useEffect(() => {
    if (!loading) {
      getList();
    }
  }, [page, pageSize, loading]);

  // 分页处理
  const Change = (page: number, pageSize: number) => {
    setPage(page);
    setPageSize(pageSize);
  };

  // 表格列定义（以后端 house 字段为准）
  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '房屋编号', dataIndex: 'houseNo', key: 'houseNo' },
    { title: '位置', dataIndex: 'location', key: 'location' },
    { title: '房东', dataIndex: 'owner', key: 'owner' },
    { title: '状态', dataIndex: 'status', key: 'status' },
    { title: '面积(㎡)', dataIndex: 'area', key: 'area' },
    { title: '租金(元)', dataIndex: 'rent', key: 'rent' },
    { title: '租期(月)', dataIndex: 'leaseTerm', key: 'leaseTerm' },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          {isAdmin && <Button onClick={() => bj(record)}>编辑</Button>}
          {isAdmin && (
            <Popconfirm
              title="提示"
              description="你确定删除吗?"
              onConfirm={() => confirm(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button danger>删除</Button>
            </Popconfirm>
          )}
          {!isAdmin && <span style={{ color: '#999' }}>仅查看</span>}
        </Space>
      ),
    },
  ];

  // 所有列居中
  const columnsCentered = columns.map((col:any) => ({ ...col, align: 'center' as const }));

  // 删除功能（DELETE /api/house/:id）
  const confirm = async (record: any) => {
    try {
      await pp.delete(`/api/house/${record.id}`)
      message.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      message.error('删除失败')
    }
  };

  // 添加按钮
  const add = () => {
    settitle('添加')
    setOpen(true)
    form.resetFields()
    setId('')
  };

  // 编辑按钮
  const bj = (record: any) => {
    settitle('编辑')
    setOpen(true)
    form.setFieldsValue(record)
    setId(record.id)
  };

  // 关闭抽屉
  const onClose = () => {
    setOpen(false);
  };

  // 添加/编辑提交（POST /api/house, PUT /api/house/:id）
  const onFinish = async (values: any) => {
    try {
      if (title === '添加') {
        await pp.post('/api/house', values)
        message.success('添加成功')
      } else if (title === '编辑') {
        await pp.put(`/api/house/${id}`, values)
        message.success('编辑成功')
      }
      setOpen(false)
      getList()
    } catch (error: any) {
      console.error('操作失败:', error)
      const msg = error?.response?.data?.message || '操作失败'
      message.error(msg)
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  // 搜索功能（GET /api/house/search?keyword=...）
  const onFinish1 = async (values: any) => {
    try {
      const res = await pp.get('/api/house/search', {
        params: { keyword: values.keyword, page, pageSize }
      })
      const data = res?.data?.data
      const rows = data?.list || []
      const totalCount = data?.total || 0
      setList(rows)
      setTotal(totalCount)
    } catch (error) {
      console.error('搜索失败:', error)
      message.error('搜索失败')
    }
  };

  return (
    <div>
      {loading ? (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 360 }}>
          <Spin size="large" tip="加载中..." />
        </div>
      ) : (
        <>
          {/* 标题区域 */}
          <div style={{ background:'#fff', padding:'16px 20px', borderRadius:8, marginBottom:16 }}>
            <div style={{ fontSize:16, fontWeight:600, color:'#1d2129', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <div>
                后台管理 - 订单管理
                <div style={{ width:60, height:3, background:'#1677ff', borderRadius:2, marginTop:8 }} />
              </div>
              <Space>
                {isAdmin && <Button icon={<PlusOutlined />} type="primary" onClick={add}>添加</Button>}
                {isAdmin && <Button icon={<DownloadOutlined />}>导出</Button>}
                {!isAdmin && <span style={{ color: '#999', fontSize: 14 }}>普通用户仅可查看</span>}
              </Space>
            </div>
          </div>

          {/* 筛选工具栏 */}
          <div style={{ background:'#fff', padding:'12px 20px', borderRadius:8, marginBottom:16 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <Form
                name="search"
                layout='inline'
                style={{ flex:1 }}
                initialValues={{ remember: true }}
                onFinish={onFinish1}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
              >
                {/* <Form.Item label="申请日期" name="dateRange">
                  <DatePicker.RangePicker />
                </Form.Item>
                <Form.Item label="部门" name="dept">
                  <Select style={{ width: 160 }} placeholder="请选择部门" options={[
                    { value: '研发', label: '研发' },
                    { value: '市场', label: '市场' },
                    { value: '财务', label: '财务' },
                  ]} />
                </Form.Item> */}
                <Form.Item label="" name="keyword">
                  <Input placeholder="请输入关键词（编号/小区/位置/房东/产权编号）" style={{ width: 500 }} />
                </Form.Item>
                <Form.Item>
                  <Space>
                    <Button type="primary" icon={<SearchOutlined />} htmlType="submit">查询</Button>
                    <Button onClick={() => { form.resetFields(); getList(); }}>重置</Button>
                  </Space>
                </Form.Item>
              </Form>
            </div>
          </div>

          {/* 编辑/添加抽屉 */}
          <Drawer
            title={title}
            closable={{ 'aria-label': 'Close Button' }}
            onClose={onClose}
            open={open}
            width={600}
          >
            <Form
              name="basic"
              form={form}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              style={{ maxWidth: 600 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item label="房屋编号" name="houseNo" rules={[{ required: true, message: '请输入房屋编号!' }]}>
                <Input />
              </Form.Item>
              <Form.Item label="位置" name="location" rules={[{ required: true, message: '请输入位置!' }]}>
                <Input />
              </Form.Item>
              <Form.Item label="房东" name="owner" rules={[{ required: true, message: '请输入房东!' }]}>
                <Input />
              </Form.Item>
              <Form.Item label="状态" name="status" rules={[{ required: true, message: '请选择状态!' }]}>
                <Select
                  placeholder="请选择状态"
                  style={{ width: '100%' }}
                  options={[
                    { value: '已出租', label: '已出租' },
                    { value: '空置', label: '空置' },
                    { value: '待出租', label: '待出租' },
                  ]}
                />
              </Form.Item>
              <Form.Item label="面积(㎡)" name="area" rules={[{ required: true, message: '请输入面积!' }]}>
                <Input type="number" />
              </Form.Item>
              <Form.Item label="租金(元)" name="rent" rules={[{ required: true, message: '请输入租金!' }]}>
                <Input type="number" />
              </Form.Item>
              <Form.Item label="租期(月)" name="leaseTerm">
                <Input type="number" />
              </Form.Item>
              <Form.Item label="产权编号" name="propertyNo">
                <Input />
              </Form.Item>
              <Form.Item label="描述" name="description">
                <Input />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">提交</Button>
                <Button style={{ marginLeft: 8 }} onClick={onClose}>取消</Button>
              </Form.Item>
            </Form>
          </Drawer>

          {/* 数据表格 */}
          <Table
            columns={columnsCentered}
            dataSource={list}
            rowKey="id"
            bordered
            size="small"
            scroll={{ x: 'max-content' }}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              onChange: Change,
              onShowSizeChange: Change
            }}
          />
        </>
      )}
    </div>
  );
}

export default Index;